
/**
 * 配置build时自动创建version.js插件
 * 每次打包时会自动在dist目录下生成version.js文件
 * {
 *  version：1.0.0  // 版本号
 *  date：2025-09-18T14:32:18.047Z // 时间
 * }
 */

import type { Plugin } from 'vite'
import { resolve } from 'path'
import { writeFileSync, mkdirSync } from 'fs'

interface VersionMeta {
  version: string
  date: string
}

export const buildVersionPlugin = (): Plugin => {
  return {
    name: 'build-version-plugin',
    apply: 'build',
    closeBundle() {
      const meta: VersionMeta = {
        version: `1.0.${Date.now()}`,
        date: new Date().toISOString(),
      }
      const distDir = resolve(process.cwd(), 'dist')
      mkdirSync(distDir, { recursive: true })
      writeFileSync(resolve(distDir, 'version.json'), JSON.stringify(meta, null, 2))
    },
  }
}
